import re
from PyPDF2 import PdfReader
import pdfplumber

def extract_text_from_pdf(pdf_path):
    """从PDF文件中提取文本内容"""
    text = ""
    # 使用pdfplumber
    # with pdfplumber.open(pdf_path) as pdf:
    #     text = "\n".join(page.extract_text() for page in pdf.pages)
    try:
        reader = PdfReader(pdf_path)
        # 遍历 PDF 的每一页
        for page in reader.pages:
            # 提取当前页的文本并追加到总字符串中
            text += page.extract_text()
        # 优化后的方法
        # text = "".join(page.extract_text() for page in reader.pages)
    except Exception as e:
        print(f"读取PDF文件时出错: {e}")
    return text

def calculate_total_amount(text):
    """从文本中提取金额并计算总和"""
    # 匹配格式：支出 余额宝 300.00
    pattern = r'(收入|支出)[\s\S]*?(\d+\.\d{2})'
    matches = re.findall(pattern, text)

    total = 0.0
    for direction, amount_str in matches:
        amount = float(amount_str)
        if direction == "支出":
            amount = -amount  # 支出记为负数
        total += amount

    return total, len(matches)


def main():
    pdf_path1 = r"D:\myself\支付宝交易明细(20241030-20250527).pdf"
    pdf_path2 = r"D:\myself\支付宝交易明细(20241101-20250527).pdf"

    print(f"正在处理文件: {pdf_path1}")
    text1 = extract_text_from_pdf(pdf_path1)
    if not text1:
        print("未能从PDF中提取文本内容")
        return

    print(f"正在处理文件: {pdf_path2}")
    text2 = extract_text_from_pdf(pdf_path2)
    if not text2:
        print("未能从PDF中提取文本内容")
        return

    total_amount, count = calculate_total_amount(text1)
    print(f"共找到 {count} 笔交易记录")
    print(f"净收支合计: ¥{total_amount:.2f}")  # 正数为净收入，负数为净支出

    total_amount1, count1 = calculate_total_amount(text2)
    print(f"共找到 {count1} 笔交易记录")
    print(f"净收支合计: ¥{total_amount1:.2f}")  # 正数为净收入，负数为净支出
    #-172.8
    print(f"总共净收支合计：¥{total_amount1+total_amount:.2f}")

if __name__ == "__main__":
    main()